<template>
  <div class="edit-box">
    <el-form :model="form" :inline="true" label-position="top">
      <el-form-item label="报销人">
        <el-select
          v-model="form.userId"
          filterable
          remote
          reserve-keyword
          placeholder="请输入关键词"
          :remote-method="remoteUserList"
          :loading="loading"
        >
          <el-option
            v-for="item in userList"
            :key="item.id"
            :label="item.userName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="报销时间">
        <el-date-picker
          v-model="form.date"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="关联项目">
        <el-select
          v-model="form.projectId"
          filterable
          remote
          reserve-keyword
          placeholder="请输入关键词"
          :remote-method="remoteProjectList"
          :loading="loading"
        >
          <el-option
            v-for="item in projectList"
            :key="item.id"
            :label="item.projectName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 列表数据 -->
      <div class="list-box">
        <el-table :data="form.reimbursementDetaileds" stripe class="table-list">
          <el-table-column label="关联客户/供应商" width="150px">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.customerId"
                filterable
                remote
                reserve-keyword
                placeholder="请输入关键词"
                :remote-method="remoteCustomerList"
                :loading="loading"
              >
                <el-option
                  v-for="item in customerList"
                  :key="item.id"
                  :label="item.customerName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="关联任务">
            <template slot-scope="scope">
              <el-select v-model="scope.row.task" placeholder="请选择">
                <el-option
                  v-for="item in taskOptions"
                  :key="item.val"
                  :label="item.title"
                  :value="item.val"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="费用类别">
            <template slot-scope="scope">
              <el-cascader
                v-model="scope.row.typeMenuId"
                :show-all-levels="false"
                :options="feeTypeOptions"
                :props="{value: 'id',label: 'name', checkStrictly: true, emitPath: false}"
              ></el-cascader>
            </template>
          </el-table-column>
          <el-table-column label="发生日期" width="180px">
            <template slot-scope="scope">
              <el-date-picker
                v-model="scope.row.date"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
              ></el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="收款方" width="150px">
            <template slot-scope="scope">
              <el-input v-model="scope.row.payee"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="费用事由" width="300px">
            <template slot-scope="scope">
              <el-input v-model="scope.row.reason"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="金额">
            <template slot-scope="scope">
              <el-input v-model.number="scope.row.money"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="有无发票">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.invoice" active-value="1" inactive-value="0"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="附件">
            <template slot-scope="scope">
              <el-upload
                class="upload-demo"
                action="https://jsonplaceholder.typicode.com/posts/"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                multiple
                :limit="3"
                :on-exceed="handleExceed"
                :file-list="scope.row.fileList"
              >
                <el-button icon="el-icon-paperclip">上传</el-button>
              </el-upload>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="text" @click="del(scope.row)">
                <i class="el-icon-delete"></i>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="add-btn-box">
          <el-link type="primary" @click="addFee" :underline="false">
            <i class="el-icon-plus"></i> 添加费用
          </el-link>
        </div>
        <div class="submit-box">
          <span class="fr">合计：{{ sumMoney }} 元</span>
        </div>
      </div>
      <el-form-item label="备注">
        <el-input type="textarea" :rows="2" v-model="form.remark"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="$emit('changeState',false)">取 消</el-button>
      <el-button type="primary" @click="submit">保存</el-button>
    </div>
  </div>
</template>
<script>
import * as math from 'mathjs'
import { dateFormat } from '@/utils/index'
import { update, findById } from '@/api/dispatch'
import { findByNameLike as findCustomerList } from '@/api/customer'
import { findByNameLike as findProjectList } from '@/api/project'
import { findList as findCategoryList } from '@/api/category'
import { getListByName } from '@/api/user'
export default {
  data() {
    return {
      loading: false,
      form: {
        id: '',
        companyId: this.$store.state.user.companyId,
        userId: '',
        date: '',
        projectId: '',
        remark: '',
        reimbursementDetaileds: []
      },
      userList: [],
      feeTypeOptions: [],
      projectList: [],
      customerList: [],
      taskOptions: [
        {
          val: '0',
          title: '计划分派'
        },
        {
          val: '1',
          title: '临时任务'
        },
        {
          val: '2',
          title: '自主安排'
        }
      ]
    }
  },
  computed: {
    sumMoney() {
      return this.form.reimbursementDetaileds.reduce((sum, res) => {
        return math.add(sum, res.money).toFixed(2)
      }, 0)
    }
  },
  beforeDestroy() {
    this.$off('reload')
    this.$off('changeState')
  },
  methods: {
    initDialogData(id) {
      this.initTypeOptions()
      this.remoteProjectList('')
      this.remoteUserList('')
      this.remoteCustomerList('')
      findById(id).then(res => {
        this.form = res.data
      })
    },
    // 获取费用类别列表
    initTypeOptions() {
      let params = { companyId: this.form.companyId, type: 0 }
      findCategoryList(params).then(res => {
        this.feeTypeOptions = res.data
      })
    },
    // 获取用户列表
    remoteUserList(query) {
      this.loading = true
      let params = { companyId: this.form.companyId, userName: query }
      getListByName(params).then(res => {
        this.loading = false
        this.userList = res.data
      })
    },
    // 获取客户列表
    remoteCustomerList(query) {
      this.loading = true
      let params = { companyId: this.form.companyId, customerName: query }
      findCustomerList(params).then(res => {
        this.loading = false
        this.customerList = res.data
      })
    },
    // 获取项目列表
    remoteProjectList(query) {
      this.loading = true
      let params = { companyId: this.form.companyId, projectsName: query }
      findProjectList(params).then(res => {
        this.loading = false
        this.projectList = res.data
      })
    },
    // 添加一行费用数据
    addFee() {
      let obj =
        this.form.reimbursementDetaileds.length > 0 ? this.form.reimbursementDetaileds[this.form.reimbursementDetaileds.length - 1] : null
      this.form.reimbursementDetaileds.push({
        id: '',
        companyId: this.$store.state.user.companyId,
        customerId: obj == null ? '' : obj.customerId,
        task: obj == null ? '' : obj.task,
        date: dateFormat(new Date()),
        typeMenuId: obj == null ? '' : obj.typeMenuId,
        payee: obj == null ? '' : obj.payee,
        reason: '',
        money: 0,
        invoice: 0,
        fileList: []
      })
    },
    // 删除一行费用数据
    del(row) {
      this.form.reimbursementDetaileds.splice(
        this.form.reimbursementDetaileds.indexOf(row),
        1
      )
    },
    submit() {
      this.form.money = this.sumMoney
      update(this.form).then(res => {
        if (res.success) {
          this.$emit('reload')
          this.$emit('changeState', false)
          this.$message.success(res.message)
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 以下附件上传相关，根据情况删减
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    }
  }
}
</script>
<style lang="scss" scoped>
.edit-box {
  padding: 0 50px;
  overflow-y: auto;
}
.dialog-footer {
  text-align: right;
}
.el-form--inline .el-form-item {
  width: calc(50% - 12px);
}
.list-box {
  margin-bottom: 15px;
}
.add-btn-box {
  height: 50px;
  line-height: 50px;
}
.submit-box {
  @extend .add-btn-box;
  font-size: 18px;
}
</style>
